<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" label-width="68px">
      <el-form-item label="商品标题" prop="subject">
        <el-input
          v-model="queryParams.subject"
          placeholder="请输入商品标题"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="卖家账户" prop="storeId">
        <el-select
          v-model="queryParams.storeId"
          placeholder="请选择"
          clearable
          @change="getList"
        >
          <el-option
            v-for="dict in storeList"
            :key="dict.value"
            :label="dict.lable"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="商品状态" prop="collectProductStatus">
        <el-select
          v-model="queryParams.collectProductStatus"
          placeholder="请选择"
          clearable
          @change="getList"
        >
          <el-option
            v-for="dict in commodityList"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="产品状态" prop="productStatusType">
        <el-select
          v-model="queryParams.productStatusType"
          placeholder="请选择"
          clearable
          @change="getList"
        >
          <el-option
            v-for="dict in productStatusList"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="ProductlD" prop="aeProductId">
        <el-input
          v-model="queryParams.aeProductId"
          placeholder="请输入ProductlD"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="产品ID" prop="collectProductId">
        <el-input
          v-model="queryParams.collectProductId"
          placeholder="请输入产品ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        <el-button :disabled="multiple" v-if="queryParams.storeId" type="primary" icon="el-icon-bottom" size="mini"
                   @click="batchOff('0')">批量下架
        </el-button>
        <el-button :disabled="multiple" v-if="queryParams.storeId" type="primary" icon="el-icon-top" size="mini"
                   @click="batchOff('1')">批量上架
        </el-button>
        <el-button type="danger" :disabled="multiple" icon="el-icon-top" size="mini" @click="handleDelete">批量删除
        </el-button>
      </el-form-item>
    </el-form>

    <el-table v-loading="loading" :data="onlineProductList" @selection-change="handleSelectionChange" border stripe>
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="基本信息" min-width="250">
        <template slot-scope="scope">
          <div class="basic-div">
            <div class="basic-div-image" v-if="scope.row.imageURLs">
              <!--              <image-preview :src="scope.row.white" :width="60" :height="60"/>-->
              <image-preview :src="scope.row.imageURLs.split(';')[0]" :width="60" :height="60"/>
            </div>
            <div class="basic-div-info span-text">
              <div class="title-text">{{ scope.row.subject }}</div>
              <span class="text-i">账号：{{ storeName(scope.row.storeId) }}</span>
              <span class="text-i">ProductlD：{{ scope.row.aeProductId }}</span>
              <span class="text-i">产品ID：{{ scope.row.collectProductId }}</span>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="销售" min-width="150">
        <template slot-scope="scope">
          <div class="span-text">
            <span class="text-i">价格：{{ scope.row.productPrice }}</span>
            <span class="text-i">加价类型：{{
                scope.row.expand.priceAdjustmentMethod == '0' ? '手动定价' : '智能定价'
              }}</span>
            <span class="text-i"
                  v-if="scope.row.expand.priceAdjustmentMethod == '0'">加价比例：{{
                scope.row.expand.readjustPricesType == '0' ? '-' : ''
              }}{{ scope.row.expand.readjustPrices }}</span>
            <span class="text-i" v-if="scope.row.expand.priceAdjustmentMethod == '1'">加价模板：{{
                scope.row.expand.templateName
              }}</span>
            <span class="text-i">销量：0</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="状态" min-width="150">
        <template slot-scope="scope">
          <div class="span-text">
            <span class="text-i">商品状态：<i>{{ productStatusType(scope.row.expand.productStatusType) }}</i></span>
            <span class="text-i">发布状态：<i>{{ releaseStatus(scope.row.expand) }}</i></span>
            <span class="text-i">产品状态：<i>{{
                scope.row.collectProductStatus == '1' ? 'ERP在售' : 'ERP下架'
              }}</i></span>
            <span v-if="scope.row.expand && scope.row.expand.activityRemark"
                  class="text-i">活动折扣：{{ scope.row.expand.activityRemark }}</span>

          </div>
        </template>
      </el-table-column>
      <el-table-column label="日期" width="250">
        <template slot-scope="scope">
          <div class="span-text">
            <span class="text-i">创建时间：{{ scope.row.createTime }}</span>
            <span class="text-i">最后修改时间：{{ scope.row.updateTime }}</span>
            <span class="text-i">最后修改人：{{ scope.row.updateBy }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="100">
        <template slot-scope="scope">
          <div class="nomargin">
            <!-- <el-button
              size="mini"
              type="text"
            >编辑</el-button> -->

            <el-button size="mini" type="text" @click="openEvaluation(scope.row)">测评</el-button>
            <el-button size="mini" type="text" @click="handleFission(scope.row)">裂变</el-button>
            <el-button size="mini" type="text" @click="openProductDrawer(scope.row.id)">查看</el-button>
            <el-button size="mini" type="text" @click="handleLog(scope.row)">日志</el-button>
            <el-button v-if="scope.row.expand.productStatusType == '1' && scope.row.collectProductStatus == '0'"
                       size="mini" type="text" @click="handleOff(scope.row, '1')">上架
            </el-button>
            <el-button v-else size="mini" type="text" @click="handleOff(scope.row, '0')">下架</el-button>
            <el-button v-if="scope.row.expand.status == '3'" size="mini" type="text" @click="handleUp(scope.row)">
              重新上架
            </el-button>
            <el-button v-if="scope.row.expand.status == '3' || scope.row.expand.status == '0'" size="mini" type="text"
                       @click="handleDelete(scope.row)">
              删除
            </el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 商品详情 -->
    <el-drawer
      title="商品详情"
      :visible.sync="drawer"
      direction="rtl"
      size="48%"
      :before-close="handleClose"
      custom-class="demo-drawer"
      destroy-on-close
      ref="drawer"
    >
      <div class="demo-drawer__content">
        <el-form :model="detailsForm" ref="detailsForm" :rules="detailsRules" :inline="true" label-width="100px">
          <el-row>
            <div>
              <el-col :span="24">
                <div class="title">基本信息</div>
              </el-col>
              <el-col :span="24">
                <el-form-item label="商品属性" prop="productAttribute">
                  <el-select disabled v-model="detailsForm.expand.productAttribute">
                    <el-option
                      v-for="dict in dict.type.erp_product_attribute"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="商品类目" prop="categoryId">
                  <el-cascader
                    v-model="detailsForm.categoryId"
                    :options="categoryList"
                    :props="{ value: 'id', label: 'name', checkStrictly: true }"
                    disabled
                  >
                  </el-cascader>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="商品单位" prop="productUnit">
                  <el-select v-model="detailsForm.productUnit" disabled>
                    <el-option
                      v-for="dict in dict.type.ae_product_unit"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value*1"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="品牌选择" prop="brandId">
                  <el-select disabled v-model="detailsForm.expand.brandId">
                    <el-option
                      v-for="dict in brandList"
                      :key="dict.value"
                      :label="dict.lable"
                      :value="dict.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col v-if="newClassifyList.length > 0" :span="24">
                <el-form-item class="flexbox" label="商品标签" prop="classifyLabel">
                  <div class="border-box">
                    <el-tag
                      v-for="(tag) in newClassifyList"
                      :key="tag.value"
                    >
                      {{ tag.lable }}
                    </el-tag>
                  </div>
                </el-form-item>
              </el-col>
              <!-- <el-col :span="24">
                <el-form-item class="text-input" label="包装毛重" prop="grossWeight">
                  <el-input v-model="detailsForm.grossWeight" disabled placeholder="" />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item class="flexbox flex" label="包装尺寸" prop="packageLength">
                  <el-input v-model="detailsForm.packageLength" disabled placeholder="" /><span class="span">X</span>
                  <el-input v-model="detailsForm.packageWidth" disabled placeholder="" /><span class="span">X</span>
                  <el-input v-model="detailsForm.packageHeight" disabled placeholder="" /><span class="span">cm</span>
                </el-form-item>
              </el-col> -->
              <el-col :span="24">
                <el-form-item class="flexbox" label="商品主图" prop="imageURLs">
                  <div class="border-box" style="display: flex; flex-wrap: wrap;">
                    <div style="margin: 10px;" v-for="(item, index) in detailsForm.imageURLs" :key="index">
                      <image-preview
                        :src="item"
                        :width="140"
                        :height="140"
                      />
                    </div>
                  </div>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="白底图" prop="white">
                  <div class="border-box" style="display: flex; flex-wrap: wrap;">
                    <div style="margin: 10px;" v-for="(item, index) in detailsForm.white" :key="index">
                      <image-preview
                        :src="item"
                        :width="140"
                        :height="140"
                      />
                    </div>
                  </div>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="营销图" prop="marketing">
                  <div class="border-box" style="display: flex; flex-wrap: wrap;">
                    <div style="margin: 10px;" v-for="(item, index) in detailsForm.marketing" :key="index">
                      <image-preview
                        :src="item"
                        :width="140"
                        :height="140"
                      />
                    </div>
                  </div>
                </el-form-item>
              </el-col>
              <el-col v-if="detailsForm.media" :span="24">
                <el-form-item label="商品视频" prop="media">
                  <div class="border-box">
                    <video controls style="width: 300px; height: 200px;" :src="media"></video>
                    <!-- <video src="https://cloud.video.taobao.com/play/u/3364946291/p/2/e/6/t/1/262060154386.mp4"></video> -->
                  </div>
                </el-form-item>
              </el-col>
              <el-col v-if="Array.isArray(detailsForm.customAttributes)" :span="24">
                <el-form-item class="flexbox" label="产品属性" prop="">
                  <div class="border-box">
                    <el-form-item
                      v-for="(item, index) in detailsForm.customAttributes"
                      :key="index"
                      class="flexbox"
                      :label="item.zhName"
                      label-width="240px"
                    >
                      <div class="box-input-item width-input">
                        <el-input
                          v-if="item.attributeShowTypeValue == 'input'"
                          v-model.trim="item.attr_value"
                          placeholder="请输入"
                          disabled
                        />
                        <el-select v-if="item.attributeShowTypeValue == 'list_box'" v-model="item.attr_value_id"
                                   disabled>
                          <el-option
                            v-for="dict in item.values"
                            :key="dict.attr_value_id"
                            :label="dict.zhName"
                            :value="dict.attr_value_id"
                          />
                        </el-select>
                        <el-select v-if="item.attributeShowTypeValue == 'check_box'" multiple
                                   v-model="item.attr_value_id" disabled>
                          <el-option
                            v-for="dict in item.values"
                            :key="dict.attr_value_id"
                            :label="dict.zhName"
                            :value="dict.attr_value_id"
                          />
                        </el-select>
                      </div>
                    </el-form-item>
                  </div>
                </el-form-item>
              </el-col>
            </div>
            <div v-if="newSkuList.length > 0">
              <el-col :span="24">
                <div class="title">规格库存</div>
              </el-col>
              <el-col :span="24">
                <el-form-item class="flexbox" label="商品规格" prop="">
                  <div class="border-box">
                    <div class="tagBox">
                      <div
                        v-for="(item) in JSON.parse(detailsForm.expand.skuProperty || '[]')"
                        :key="item.value"
                        class="tagBox-item"
                      >
                        <div class="tagBox-item-name">
                          <span class="name-text">{{ item.name }}</span>
                        </div>
                        <div class="tagBox-item-list">
                          <template v-if="item.list.length > 0">
                            <el-tag
                              v-for="(tag) in item.list"
                              :key="tag.value"
                            >
                              {{ tag.name }}
                            </el-tag>
                          </template>
                        </div>
                      </div>
                    </div>
                  </div>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <div class="paddingLeft-box">
                  <el-table
                    :data="newSkuList"
                    border
                    :header-cell-style="{'text-align':'center'}"
                    :cell-style="{'text-align':'center'}"
                    header-cell-class-name="table-header"
                    width="100%"
                    current-row-key="uid"
                    row-class-name="table-row">
                    <template v-if="detailsForm.expand">
                      <el-table-column
                        v-for="(leftTitle) in JSON.parse(detailsForm.expand.skuProperty || '[]')"
                        :key="leftTitle.value"
                        :label="leftTitle.name">
                        <template slot-scope="scope">
                          {{ propertyLabel(scope.row.skuPropertyIds, leftTitle.value) }}
                        </template>
                      </el-table-column>
                    </template>
                    <el-table-column prop="skuImage" label="sku图片" width="120">
                      <template slot-scope="scope">
                        <el-form-item>
                          <image-preview :src="scope.row.skuImage" :width="80" :height="80"/>
                        </el-form-item>
                      </template>
                    </el-table-column>
                    <!-- <el-table-column prop="collectSkuPrice" label="sku采集价格">
                      <template slot-scope="scope">
                        <el-form-item>
                          <el-input disabled v-model="scope.row.collectSkuPrice"></el-input>
                        </el-form-item>
                      </template>
                    </el-table-column>
                    <el-table-column prop="skuLength" label="sku长度" width="100">
                      <template slot-scope="scope">
                        <el-form-item>
                          <el-input disabled v-model="scope.row.skuLength"></el-input>
                        </el-form-item>
                      </template>
                    </el-table-column>
                    <el-table-column prop="skuWidth" label="sku宽度" width="100">
                      <template slot-scope="scope">
                        <el-form-item>
                          <el-input disabled v-model="scope.row.skuWidth"></el-input>
                        </el-form-item>
                      </template>
                    </el-table-column>
                    <el-table-column prop="skuHeight" label="sku高度" width="100">
                      <template slot-scope="scope">
                        <el-form-item>
                          <el-input disabled v-model="scope.row.skuHeight"></el-input>
                        </el-form-item>
                      </template>
                    </el-table-column> -->
                    <el-table-column prop="skuStock" label="sku库存">
                      <template slot-scope="scope">
                        <el-form-item>
                          <el-input-number disabled v-model="scope.row.skuStock" step-strictly :controls="false"
                                           :min="0"></el-input-number>
                        </el-form-item>
                      </template>
                    </el-table-column>
                  </el-table>
                </div>
              </el-col>
              <el-col v-if="checkedCities.length > 0" :span="24">
                <el-form-item class="flexbox" label="区域定价" prop="">
                  <div class="border-box">
                    <div class="tagBox">
                      <div class="tagBox-item">
                        <div class="tagBox-item-list">
                          <el-tag
                            v-for="tag in checkedCities"
                            :key="tag.lable"
                            :disable-transitions="false">
                            {{ tag.value }}[{{ tag.lable }}]
                          </el-tag>
                        </div>
                      </div>
                    </div>
                  </div>
                </el-form-item>
              </el-col>
              <el-col v-if="checkedCities.length > 0" :span="24">
                <div class="paddingLeft-box">
                  <el-table
                    :data="newAreaList"
                    border
                    :header-cell-style="{'text-align':'center'}"
                    :cell-style="{'text-align':'center'}"
                    header-cell-class-name="table-header"
                    width="100%"
                    current-row-key="uid"
                    row-class-name="table-row">
                    <template v-if="detailsForm.expand">
                      <el-table-column
                        v-for="(leftTitle) in JSON.parse(detailsForm.expand.skuProperty || '[]')"
                        :key="leftTitle.value"
                        :label="leftTitle.name"
                      >
                        <template slot-scope="scope">
                          {{ propertyLabel(scope.row.skuPropertyIds, leftTitle.value) }}
                        </template>
                      </el-table-column>
                    </template>
                    <el-table-column
                      v-for="(leftTitle) in absoluteQuoteMap"
                      :key="leftTitle.shiptoCountry"
                      :label="leftTitle.shiptoCountry"
                    >
                      <template slot-scope="scope">
                        <el-form-item :prop="absoluteQuoteMapProp(scope.row, leftTitle)">
                          <el-input
                            disabled
                            :value="absoluteQuoteMapValue(scope.row, leftTitle)"
                          />
                        </el-form-item>
                      </template>
                    </el-table-column>
                  </el-table>
                </div>
              </el-col>
            </div>
            <div>
              <el-col :span="24">
                <div class="title">商品详情</div>
              </el-col>
              <el-col :span="24">
                <el-form-item class="flexbox" label="商品名称" prop="subject">
                  <el-input v-model="detailsForm.subject" placeholder="请输入商品名称" disabled/>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item class="flexbox" label="商品详情" prop="detail">
                  <el-input v-model="detailsForm.detail" type="textarea" :autosize="{ minRows: 2, maxRows: 12}"
                            placeholder="请输入商品详情" disabled/>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item class="flexbox" label="商品详情图" prop="detailImg">
                  <div class="border-box" style="display: flex; flex-wrap: wrap;">
                    <div style="margin: 10px;" v-for="(item, index) in detailsForm.detailImg" :key="index">
                      <image-preview
                        :src="item"
                        :width="140"
                        :height="140"
                      />
                    </div>
                  </div>
                </el-form-item>
              </el-col>
            </div>
          </el-row>
        </el-form>
      </div>
    </el-drawer>
    <!--  测评提交表单  -->
    <EvaluationForm v-if="isOpenEvaluation" @evaluationSwitch="evaluationSwitch"
                    :productSkuList="productSkuList" :type="type"
                    :evaluationBalance="evaluationBalance"/>
  </div>
</template>

<script>
import {
  listSellerStoreProduct,
  getSellerStoreProduct,
  fission,
  productOfflineOrOnline,
  getSkuNameById,
  restartPublish,
  storeProductDelete,
  getWalletExpend
} from "@/api/product/online/list";
import {queryUserShopList} from "@/api/shop/index";
import {getSelect, getArea, getBrand, categoryInfo} from "@/api/attribute";
import {selectlistCollectProductCategory} from "@/api/gather/collectProductCategory";
import EvaluationForm from "@/views/product/components/EvaluationForm.vue";

export default {
  components: {
    EvaluationForm
  },
  name: "SellerStoreProduct",
  dicts: ['ae_product_unit', 'erp_product_attribute'],
  data() {
    return {
      type: undefined,//是否是从公司刷单页面跳转
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      aeProductIds: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 卖家商品
      sellerProductList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        subject: undefined,
        storeId: undefined,
        collectProductStatus: undefined,
        productStatusType: undefined,
        aeProductId: undefined,
        collectProductId: undefined
      },
      onlineProductList: [],
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
      isCheckAll: false, // 全选
      // 全选
      isIndeterminate: false,
      drawer: false, // 商品详情弹框
      productId: null, // 商品id
      detailsForm: {
        'expand': {
          'brandId': null,
          'skuProperty': '[]',
          'productAttribute': null
        }
      },
      detailsRules: {},
      categoryList: [], // 类目列表
      brandList: [], // 品牌列表
      classifyList: [], // 全部标签列表
      newClassifyList: [],
      customAttributes: [], // 属性值
      areaList: [], // 全部区域列表
      storeList: [],// 卖家列表
      commodityList: [
        {
          value: '-1',
          label: '等待发布'
        },
        {
          value: '-2',
          label: '发布失败'
        },
        {
          value: '-3',
          label: '疑似侵权'
        },
        {
          value: '0',
          label: '审核通过'
        },
        {
          value: '1',
          label: '下架'
        },
        {
          value: '2',
          label: '审核中'
        },
        {
          value: '3',
          label: '审核不通过'
        },
        {
          value: '4',
          label: '疑似下架'
        },
        {
          value: '5',
          label: '系统下架'
        },
        {
          value: '6',
          label: '删除'
        }
      ], // 产品状态
      productStatusList: [
        {
          value: '0',
          label: 'ERP下架'
        },
        {
          value: '1',
          label: 'ERP在售'
        }
      ], // 产品状态
      isOpenEvaluation: false,//是否打开测评弹窗
      productSkuList: [],//产品规格Id列表
      evaluationBalance: "",//测评余额
    };
  },
  computed: {
    // 账户
    storeName() {
      return (val) => {
        var storeName = ''
        for (var i = 0; i < this.storeList.length; i++) {
          if (val == this.storeList[i].value) {
            storeName = this.storeList[i].lable
          }
        }
        return storeName
      }
    },
    // 商品状态
    productStatusType() {
      return (val) => {
        switch (val) {
          case '0':
            return '审核通过'
          case '1':
            return '下架'
          case '2':
            return '审核中'
          case '3':
            return '审核不通过'
          case '4':
            return '疑似下架'
          case '5':
            return '系统下架'
          case '6':
            return '删除'
          case '-1':
            return '等待发布'
          case '-2':
            return '发布失败'
          case '-3':
            return '疑似侵权'
          default:
            return '异常'
        }
      }
    },
    // 发布状态
    releaseStatus() {
      return (val) => {
        switch (val.status) {
          case 0:
            return '等待发布'
          case 1:
            return '发布中'
          case 2:
            return '发布成功'
          case 3:
            return `发布失败(${val.remark})`
          default:
            return ''
        }
      }
    },
    // 视频
    media() {
      if (this.detailsForm.media.indexOf('http://') === -1 && this.detailsForm.media.indexOf('https://') === -1) {
        return this.$store.getters.domain + this.detailsForm.media;
      } else {
        return this.detailsForm.media;
      }
    },
    productList() {
      let productList = this.sellerProductList;
      productList.forEach((item) => {
        const imageURLsArr = (item.imageURLs || '').split(';').filter(i => !!i)
        const newArr = []
        imageURLsArr.forEach(val => {
          if (val.indexOf('http://') === -1 && val.indexOf('https://') === -1) {
            newArr.push(this.$store.getters.domain + val)
          } else {
            newArr.push(val)
          }
        })
        item.imageURLs = newArr.toString();
        this.$set(item, "isChecked", false);
      });
      return productList;
    },
    // sku商品
    propertyLabel() {
      if (this.detailsForm.expand) {
        const ls = JSON.parse(this.detailsForm.expand.skuProperty || '[]')
        return (ids, val) => {
          try {
            const items = ids
              .split(';').filter(item => !!item && new RegExp(`^${val}:[0-9]+`).test(item))
              .map(it => {
                const [p1, p2] = it.split(':').filter(item => !!item)
                return ls.filter(item => item.value == p1)[0].list.filter(item => item.value == p2)[0]
              })
            return items[0].name
          } catch (e) {
            return '-'
          }
        }
      } else return '-'
    },
    // sku列表数据
    newSkuList() {
      if (this.detailsForm.expand) {
        const skuProperty = JSON.parse(this.detailsForm.expand.skuProperty || '[]')
        const idsArr = []
        skuProperty.forEach((p1, p1Index) => {
          (p1.list || []).forEach((p2, p2Index) => {
            if (!idsArr[p1Index]) idsArr.push([])
            idsArr[p1Index].push(`${p1.value}:${p2.value}`)
          })
        })
        const skuPropertyIdsArr = skuPropertyPackage(idsArr, 0)
        const list = skuPropertyIdsArr.map(ids => {
          const rowData = this.getRowData(ids)
          return rowData
        })
        return list
      } else return []
    },
    // 区域定价数据
    absoluteQuoteMap: {
      get() {
        if (this.detailsForm.expand) {
          return JSON.parse(this.detailsForm.expand.absoluteQuoteMap || '[]')
        } else {
          return []
        }
      },
      set(val) {
        if (this.detailsForm.expand) {
          this.$set(this.detailsForm.expand, 'absoluteQuoteMap', JSON.stringify(val || []))
        } else {
          this.detailsForm.expand = {
            absoluteQuoteMap: JSON.stringify(val || [])
          }
        }
      }
    },
    // 区域定价的国家数据
    checkedCities() {
      const selectCountrys = this.absoluteQuoteMap.map(item => item.shiptoCountry)
      return this.areaList.filter(item => selectCountrys.includes(item.lable))
    },
    // 区域列表数据
    newAreaList() {
      // const absoluteQuoteMap = this.absoluteQuoteMap
      return this.newSkuList.map(sku => ({
        ...sku,
      }))
    },
    // 区域定价，输入框 value
    absoluteQuoteMapValue() {
      return (row, column) => {
        const value = (column.absoluteQuoteMap || {})[row.skuPropertyIds.replace(/\,/g, ';')] || '0'
        // debugger
        return value
      }
    },
    absoluteQuoteMapProp() {
      return (row, column) => {
        const prop = encodeURIComponent(`absoluteQuoteMap_${column.shiptoCountry}_${row.skuPropertyIds}`)
        // console.log(prop)
        return prop
      }
    }
  },
  created() {
    console.log('&&', this.$route.query)
    let query = this.$route.query
    if (query.type) {
      this.type = query.type
    }
    if (query.storeId) {
      this.queryParams.storeId = query.storeId
    }
    this.getList();
    this.getGoodsCategory();
    this.getBrandList();
    this.getSelectList();
    this.getAreaList();
    this.getEmpowerList();
    this.getEvaluationBalance()
  },
  methods: {
    // 获取测评余额
    getEvaluationBalance() {
      getWalletExpend({userId: this.$store.getters.userId}).then(res => {
        this.evaluationBalance = res.data
      })
    },
    // 获取店铺账号选择列表
    getEmpowerList() {
      queryUserShopList().then(res => {
        this.storeList = res.data
      });
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.aeProductIds = selection.map(item => item.aeProductId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 查询卖家商品 */
    getList() {
      this.loading = true;
      this.isCheckAll = false;
      listSellerStoreProduct(this.queryParams).then(response => {
        this.onlineProductList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 商品类目
    getGoodsCategory() {
      selectlistCollectProductCategory().then(response => {
        this.categoryList = this.handleTree(response.data, "id", "parentId");
      });
    },
    // 获取品牌选择列表
    getBrandList() {
      getBrand().then(res => {
        this.brandList = res.data
      });
    },
    // 获取商品标签的选择列表
    getSelectList() {
      getSelect().then(res => {
        this.classifyList = res.data
      });
    },
    // 获取区域定价国家选择列表
    getAreaList() {
      getArea().then(res => {
        this.areaList = res.data
      });
    },
    // 表单重置
    reset() {
      this.form = {};
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 打开商品详情弹框
    openProductDrawer(id) {
      this.productId = id
      this.loading = true;
      getSellerStoreProduct(id).then(res => {
        if (res.data.expand) {
          this.detailsForm = res.data
        } else {
          this.detailsForm = {
            ...res.data, 'expand': {
              'brandId': null,
              'skuProperty': '[]',
              'productAttribute': null
            }
          }
        }
        const categoryId = res.data.categoryId
        if (categoryId) {
          this.getCategoryInfo(categoryId);
        }
        if (this.detailsForm.imageURLs) {
          var imageURLs = this.detailsForm.imageURLs.split(';');
          // 过滤掉后缀为.mp4的照片
          imageURLs = imageURLs.filter(item => item.indexOf('.mp4') == -1);
          this.detailsForm.imageURLs = imageURLs.splice(0, 6);
        }
        if (this.detailsForm.white) {
          var white = this.detailsForm.white.split(';');
          this.detailsForm.white = white.splice(0, 1);
        }
        if (this.detailsForm.marketing) {
          var marketing = this.detailsForm.marketing.split(';');
          this.detailsForm.marketing = marketing.splice(0, 1);
        }
        if (this.detailsForm.media) {
          var media = this.detailsForm.media.split(';');
          this.detailsForm.media = media.splice(0, 1);
        }
        if (this.detailsForm.detailImg) {
          var detailImg = this.detailsForm.detailImg.split(';');
          this.detailsForm.detailImg = detailImg;
        }
        this.customAttributes = JSON.parse(res.data.customAttributes || '[]')
        if (res.data.expand && res.data.expand.classifyLabel) {
          const classifyValue = res.data.expand.classifyLabel.split(',');
          const arr = this.classifyList;
          arr.forEach(item => {
            classifyValue.forEach(chirldItem => {
              if (item.value == chirldItem) {
                this.newClassifyList.push(item);
              }
            })
          })
        } else {
          this.newClassifyList = []
        }
        this.loading = false;
        this.drawer = true;
      });
    },
    // 获取商品属性
    getCategoryInfo(id) {
      categoryInfo(id).then(res => {
        var resMap = new Map();
        res.data.forEach(item => {
          var attribute = {
            'attr_name_id': item.attr_name_id,
            'attr_name': item.attr_name,
            'zhName': item.zhName || item.attr_name,
            'attr_value_id': item.attr_value_id,
            'attr_value': item.attr_value,
            'values': item.values,
            'attributeShowTypeValue': item.attributeShowTypeValue,
            'required': item.required
          };
          resMap.set(item.attr_name_id, attribute);
        })
        var attrOther = [];
        const customAttributes = Array.isArray(this.detailsForm.customAttributes) ? this.detailsForm.customAttributes : JSON.parse(this.detailsForm.customAttributes || '[]');
        customAttributes.forEach(item => {
          if (item.attr_name_id != 2) {
            if (item.attr_name_id == -1) {
              if (item.attr_name != '' && item.attr_name != undefined) {
                item.zhName = item.attr_name;
                item.attr_value_id = -1;
                item.values = undefined;
                item.attributeShowTypeValue = 'input';
                item.required = '0';
                attrOther.push(item);
              }
            } else {
              var attribute = resMap.get(item.attr_name_id);
              if (attribute == undefined) {
                attribute = {
                  'attr_name_id': -1,
                  'attr_name': item.attr_name,
                  'zhName': item.attr_name,
                  'attr_value_id': -1,
                  'attr_value': item.attr_value,
                  'values': [],
                  'attributeShowTypeValue': 'input',
                  'required': 0
                };
                resMap.set(item.attr_name_id, attribute);
              } else {
                if (item.attr_value_id != -1) {
                  // 获取是否有值
                  if (attribute.attributeShowTypeValue == 'check_box') {
                    var attr_value_id = attribute.attr_value_id;
                    if (attr_value_id == undefined) {
                      attribute.attr_value_id = [item.attr_value_id];
                    } else {
                      attribute.attr_value_id.push(item.attr_value_id);
                    }
                  } else {
                    attribute.attr_value_id = item.attr_value_id;
                    attribute.attr_value = item.attr_value;
                  }
                }
              }
            }
          }
        });
        var attr = [];
        resMap.forEach((key, val) => {
          attr.push(key);
        });
        attr.sort((a, b) => Number(b.required) - Number(a.required));
        attr = [...attr, ...attrOther];
        this.$set(this.detailsForm, 'customAttributes', attr);
      });
    },
    // 关闭商品详情弹框
    handleClose() {
      this.drawer = false;
    },
    getRowData(ids) {
      const idsArr = ids.split(',').filter(item => !!item)
      const item = this.detailsForm.skuList.filter(item => {
        const skuPropertyIds = item.skuPropertyIds.split(';').filter(item => !!item)
        return ArrayIsSame(skuPropertyIds, idsArr)
      })[0]
      if (item) {
        item.uid = item.id
        return item
      } else {
        return {
          uid: this.$getUuid(),
          collectSkuPrice: null,
          skuImage: null,
          skuPrice: null,
          skuStock: null,
          skuLength: null,
          skuHeight: null,
          skuWidth: null,
          skuPropertyIds: ids.toString()
        }
      }
    },
    // 日志
    handleLog(row) {

    },
    // 上架下架
    handleOff(row, e) {
      if (e == '1' && row.collectProductStatus == '0') {
        this.$modal.msgError("ERP内商品已下架，上架到速卖通失败");
        return;
      }
      const text = e == '1' ? '上架' : '下架'
      this.$confirm('是否对此商品进行' + text + '?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const params = {
          sellerStoreProductIds: row.aeProductId,
          sellerId: row.storeId,
          type: e
        }
        productOfflineOrOnline(params).then(res => {
          this.getList();
          this.$modal.msgSuccess(res.msg);
        })
      }).catch(() => {
        this.$modal.msgError(res.msg);
      });
    },
    // 重新上架
    handleUp(row) {
      if (row.collectProductStatus == '0') {
        this.$modal.msgError("ERP内商品已下架，上架到速卖通失败");
        return;
      }

      this.$confirm('是否对此商品进行重新上架?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        restartPublish({sellerStoreProductId: row.id}).then(res => {
          this.getList();
          this.$modal.msgSuccess(res.msg);
        })
      }).catch(() => {
        this.$modal.msgError(res.msg);
      });
    },
    // 删除
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否删除此商品?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        storeProductDelete(ids).then(res => {
          this.getList();
          this.$modal.msgSuccess(res.msg);
        })
      }).catch(() => {
        this.$modal.msgError(res.msg);
      });
    },
    // 批量上架下架
    batchOff(e) {
      if (this.aeProductIds.length > 0) {
        const params = {
          sellerStoreProductIds: this.aeProductIds.join(';'),
          sellerId: this.queryParams.storeId,
          type: e
        }
        productOfflineOrOnline(params).then(res => {
          this.getList();
          this.$modal.msgSuccess(res.msg);
        })
      } else {
        this.$modal.msgWarning('请选择商品');
      }
    },
    // 裂变
    handleFission(row) {
      this.$confirm('是否对此商品进行裂变?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        fission({sellerStoreProductId: row.id}).then(res => {
          this.getList();
          this.$modal.msgSuccess(res.msg);
        })
      }).catch(() => {

      });
    },
    //   打开测评弹窗
    openEvaluation(row) {
      getSkuNameById({id: row.id}).then(res => {
        this.productSkuList = res.data
        this.isOpenEvaluation = true
      })
    },
    // 关闭测评弹窗
    evaluationSwitch(e) {
      this.isOpenEvaluation = false
      if (e == "isRef") {
        this.getList()
      }
    }
  }
};

// 相同sku比较
function ArrayIsSame(_arr1, _arr2) {
  const arr1 = [..._arr1]
  const arr2 = [..._arr2]
  // 长度比较
  if (arr1.length !== arr2.length) return false
  // 项比较
  while (arr1.length > 0) {
    if (arr2.includes(arr1[0])) {
      const index = arr2.indexOf(arr1[0])
      arr1.splice(0, 1)
      arr2.splice(index, 1)
    } else {
      return false
    }
  }
  return true
}

// 商品规格包装数据
function skuPropertyPackage(skuProperty, index = 0) {
  const ids = [];
  (skuProperty[index] || []).forEach(item => {
    const _ids = [];
    const otherIds = skuPropertyPackage(skuProperty, index + 1)
    if (otherIds.length) {
      _ids.push(...otherIds.map(child => `${item},${child}`))
    } else {
      _ids.push(item)
    }
    ids.push(..._ids)
  })
  return ids
}

</script>

<style lang="scss">
.basic-div {
  display: flex;
  align-items: flex-start;

  .basic-div-image {
    width: 60px;
  }

  .basic-div-info {
    flex: 1;
    padding: 0 15px;
  }
}

.span-text {
  .title-text {
    font-size: 14px;
    line-height: 20px;
    color: #606266;
  }

  .text-i {
    font-size: 14px;
    line-height: 20px;
    color: #999999;
    display: block;

    i {
      font-style: normal;
    }
  }
}

.nomargin {
  .el-button {
    display: block;
  }

  .el-button + .el-button {
    margin-left: 0;
  }
}

.operation {
  border-top: 1px solid #DFDFDF;
  border-bottom: 1px solid #DFDFDF;
  padding: 10px 0;
  margin: 20px 0;
  display: flex;
  align-items: center;

  .operation-item {
    position: relative;
    font-size: 14px;
    text-align: center;

    &:before {
      content: '';
      width: 1px;
      height: 16px;
      background-color: #DFDFDF;
      position: absolute;
      left: 0;
      top: 50%;
      margin-top: -8px;
    }

    .el-icon-upload2 {
      color: #FF6A07;
    }

    .active {
      color: #FF6A07;
    }

    div {
      cursor: pointer;
    }
  }
}

.sellerproduct-list {
  width: 100%;
  display: flex;
  flex-wrap: wrap;

  .sellerproduct-list-item {
    width: calc((100% - 60px) / 6);
    margin: 0 5px 10px 5px;
    cursor: pointer;

    .pCheckbox {
      width: 100%;

      .sellerproduct-list-item-image {
        width: 100%;
        height: 248px;
        object-fit: cover;
        border: 1px solid #999999;
      }
    }

    .sellerproduct-list-item-info {
      margin: 0 -5px;
      padding: 10px 0 0;

      .info-price {
        font-size: 16px;
        line-height: 20px;
        color: #1890ff;
        white-space: nowrap;
        text-overflow: ellipsis;
        overflow: hidden;
        display: block;
      }

      .info-title {
        font-size: 12px;
        line-height: 16px;
        color: #999999;
        margin-top: 5px;
        display: -webkit-box;
        -webkit-line-clamp: 4;
        -webkit-box-orient: vertical;
        overflow: hidden;
      }
    }

    .el-card__body {
      padding: 0;
    }
  }
}

.el-dialog__body {
  padding: 20px;

  .form-box {
    width: 100%;
    border: 1px solid #DFDFDF;
    border-radius: 5px;

    .form-box-header {
      background: #f2f2f2;
      padding: 10px;
      border-bottom: 1px solid #DFDFDF;
    }

    .form-box-content {
      padding: 10px;

      .item-flex-box {
        display: flex;
        align-items: center;

        .item-flex-box-input {
          flex: 1;
          padding: 0 20px;

          .item-flex-box-input-i {
            display: flex;
            align-items: center;
          }
        }
      }
    }
  }
}

.width-select-1 {
  width: 120px;
}

.width-select-2 {
  width: 200px;
}

.width-input {
  width: 200px;
}

.text {
  display: block;
  font-size: 12px;
  padding: 0 10px;
}

.color {
  color: #1890ff;
  cursor: pointer;
}

.title {
  margin: 5px 0 25px 0px;
  padding: 5px 15px;
  background-color: #f6f6f6 !important;
  line-height: 40px;
  font-size: 14px;
  text-align: left;
}

.paddingLeft-box {
  padding-left: 100px;
  width: 100%;
  margin-bottom: 22px;
}

.flexbox {
  width: 100%;
  display: flex !important;

  .el-form-item__content {
    flex: 1;
  }
}

.flex {
  .el-form-item__content {
    flex: 1;
    display: flex;
    align-items: center;

    .el-input {
      width: 80px;
    }
  }

  .span {
    font-size: 12px;
    line-height: 36px;
    color: #999999;
    padding: 0 10px;
  }
}

.showBox {
  .showBox-item {
    width: 100%;
    padding-bottom: 20px;
  }

  .showBox-button {
    display: flex;
    padding: 0 15px 20px;
  }
}

.tagBox {
  .tagBox-item {
    .tagBox-item-name {
      display: flex;
      align-items: center;

      .name-text {
        line-height: 26px;
        display: block;
      }

      .noneBorder {
        border: none;
        margin-left: 10px;
      }
    }
  }

  .el-tag {
    margin-right: 10px;
  }

  .button-new-tag {
    margin-right: 0px;
  }

  .input-new-tag {
    width: 90px;
    margin-right: 10px;
    vertical-align: bottom;
  }
}

.border-box {
  border: 1px solid #EBEEF5;
  width: 100%;
  padding: 20px;

  .title {
    margin: 0 0 10px;
  }

  .box-input-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;

    .width-input {
      .el-input {
        width: 100%;
      }
    }

    span {
      font-size: 14px;
      line-height: 36px;
      color: #999999;
      cursor: pointer;

      &:hover {
        color: #1890ff;
      }
    }
  }
}

.box-flex {
  padding-top: 30px;

  .el-form-item {
    margin-bottom: 0;
  }
}

.text-input {
  display: block;
  margin-bottom: 22px;

  .span {
    font-size: 12px;
    line-height: 36px;
    color: #999999;
    padding-left: 10px;
  }

  .el-checkbox {
    display: flex;
    align-items: center;

    .el-checkbox__input {
      padding: 0;
    }

    .el-checkbox__label {
      font-size: 12px;
      line-height: 36px;
      color: #999999;
      padding-left: 10px;
    }
  }
}

.check-box-title {
  margin-left: 80px;
  margin-bottom: 10px;
  margin-top: -10px;
}

.check-box {
  width: 55%;
  margin-left: 80px;
  margin-bottom: 30px;
  border: 1px solid #DCDFE6;
  padding: 10px;
  font-size: 12px;
  line-height: 36px;
  color: #999999;

  span {
    padding: 0 5px;
  }
}

.cell {
  .el-form-item {
    margin: 0;
  }
}

.el-drawer__body {
  overflow: hidden;

  .demo-drawer__content {
    height: 100%;
    display: flex;
    flex-direction: column;

    .el-form {
      overflow: auto;
      flex: 1;
    }

    .demo-drawer__footer {
      display: flex;
      align-items: center;
      justify-content: center;
      padding: 20px 0;
      border-top: 1px solid #DCDFE6;
    }
  }
}
</style>
